//
//  Task worker - design 2
//  Connects PULL socket to tcp://localhost:5557
//  Collects workloads from ventilator via that socket
//  Connects PUSH socket to tcp://localhost:5558
//  Sends results to sink via that socket
//
//  Adds pub-sub flow to receive and respond to kill signal
//
package main

import (
	"fmt"
	"os"
	"zmq"
	"strconv"
	"strings"
)

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()

	receiver, err := context.Socket(zmq.PULL)
	if err != nil {
		return err
	}
	defer receiver.Close()
	err = receiver.Connect("tcp://localhost:5557")
	if err != nil {
		return err
	}

	sender, err := context.Socket(zmq.PUSH)
	if err != nil {
		return err
	}
	defer sender.Close()
	err = sender.Connect("tcp://localhost:5558")
	if err != nil {
		return err
	}

	controller, err := context.Socket(zmq.SUB)
	if err != nil {
		return err
	}
	defer controller.Close()
	err = controller.Connect("tcp://localhost:5559")
	if err != nil {
		return err
	}
	err = controller.SetOptionByte(zmq.SUBSCRIBE, nil)
	if err != nil {
		return err
	}

	//  Process messages from receiver and controller
	items := make([]zmq.PollItem, 2)
	items[0].SetSocket(receiver)
	items[0].SetEvents(zmq.POLLIN)
	items[1].SetSocket(controller)
	items[1].SetEvents(zmq.POLLIN)

	for {
		zmq.Poll(items, -1)
		if items[0].GetRevents()&zmq.POLLIN == zmq.POLLIN {
			data, err := receiver.Recv(0)
			if err != nil {
				return err
			}
			ar := strings.Split(string(data), ":")
			if len(ar) != 2 {
				continue
			}
			fmt.Printf("%s.", ar[0])
			n, err := strconv.Atoi64(ar[1])
			if err != nil {
				return err
			}
			zmq.Sleep(n * 1e6)
			err = sender.Send(nil, 0)
			if err != nil {
				return err
			}
		}
		if items[1].GetRevents()&zmq.POLLIN == zmq.POLLIN {
			break
		}
	}
	return nil
}


var errch = make(chan os.Error)

func main() {
	fmt.Println("Task worker")
	exit := make(chan bool)
	go func() {
		for {
			err := <-errch
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}()
	go func() {
		err := zmq_main()
		if err != nil {
			errch <- err
		} else {	
			exit <- true
		}
	}()
	<-exit
}